<?php

namespace Admin\Controller;

use Common\Common\AdminController;
use Common\Top;
use Common\Utils;

class TourController extends AdminController
{

    public function index()
    {
        if (IS_AJAX && IS_POST) {
            $auditState = I('post.state', 0, 'int');
            $id = I('post.id', 0, 'int');
            $state = M('tour')->where('id=' . $id)->field('state,audit_memo')->find();

            $changeData['state'] = $auditState;
            $changeData['update_time'] = date("Y-m-d H:i:s", time());

            if (!$auditState && $id) {
                $data['status'] = 1;
                $data['msg'] = $state['audit_memo'];
                $this->ajaxReturn($data);
            } else {
                if ($auditState == Top::ProductStateSubmitted && $state['state'] == Top::ProductStateSubmitted) {
                    $data['status'] = 2;
                    $data['msg'] = '该产品已经提交';
                    $this->ajaxReturn($data);
                } else if ($auditState == Top::ProductStateCanceled && $state['state'] == Top::ProductStateSubmitted) {
                    $data['status'] = 3;
                    $data['msg'] = '该产品还在审核中';
                    $this->ajaxReturn($data);
                } else if ($auditState == Top::ProductStateSubmitted && $state['state'] == Top::ProductStateCanceled) {
                    $data['status'] = 4;
                    $data['msg'] = '该产品已下架';
                    $this->ajaxReturn($data);
                } else if ($auditState == Top::ProductStateCanceled && $state['state'] == Top::ProductStateRejected) {
                    $data['status'] = 5;
                    $data['msg'] = '该产品审核失败，请检查重新提交';
                    $this->ajaxReturn($data);
                } else if ($auditState == Top::ProductStateSubmitted && $state['state'] == Top::ProductStateIsSale) {
                    $data['status'] = 6;
                    $data['msg'] = '该产品已经上架，无需再次提交';
                    $this->ajaxReturn($data);
                } else if ($auditState == Top::ProductStateCanceled && $state['state'] == Top::ProductStateCanceled) {
                    $data['status'] = 7;
                    $data['msg'] = '该产品已经下架，请重新选择';
                    $this->ajaxReturn($data);
                } else if ($auditState == Top::ProductStateCanceled && $state['state'] == Top::ProductStateNotSubmitted) {
                    $data['status'] = 8;
                    $data['msg'] = '该产品还没有提交';
                    $this->ajaxReturn($data);
                } else {
                    $tour = M('tour')->where('id=' . $id)->save($changeData);
                    if ($tour) {
                        $data['status'] = 1;
                        $this->ajaxReturn($data);
                    } else {
                        $data['status'] = 0;
                        $this->ajaxReturn($data);
                    }
                }
            }
        } else {
            $nowDate = date('Y-m-d 00:00:00', strtotime('-2 day'));

            $this->assign('nowDate', $nowDate);
            $name = trim(I('get.name'));
            $nameCode = substr($name, 0, 2);

            if ($nameCode == 10 && is_numeric($name)) {
                $code = substr($name, 2);
            }
            $entityId = session('entity_id');

            if (!empty($name)) {
                $where = "provider_id = '{$entityId}' && (name like '%%$name%%' || id = '{$code}' || destination like '%%$name%%')";
            } else {
                $where = "provider_id = '{$entityId}'";
            }

            $order = "id desc ";
            $pageInfo = Utils::pages('tour', $where, C('PAGE_SET'), $order);

            $info = array(
                'info' => $pageInfo['info'],
                'page' => $pageInfo['page'],
            );

            $this->assign('name', $name);
            $this->info = $info['info'];
            $this->page = $info['page'];

            $roleId = session('role_id');
            $isAdmin = session('is_admin');

            if ($isAdmin == '0') {
                $roleInfo = M('role')->where("id = '{$roleId}'")->field('id,auth_ids')->find();
                $authIds = $roleInfo['auth_ids'];
                if (strpos($authIds, '192')) {
                    $canModifyTours = 1;
                }
            }
            $this->assign('canModifyTours', $canModifyTours);

            $this->display();
        }
    }

    /**
     * 供应商添加新的产品--基本信息
     */
    public function add()
    {

        if (IS_POST && IS_AJAX) {

            if (I('post.city')) {
                $area = M('area')->where('name=' . "'" . I('post.city') . "'")->field('id')->find();
                $city = M('area')->where('parent_id=' . $area['id'] . ' and level=2')->field('id,name')->select();
                $data = $city;
                $this->ajaxReturn($data);
            } else {
                if ($this->warnStatus == '10404') {
                    $data['status'] = 0;
                    $data['msg'] = $this->warnInfo;
                    $this->ajaxreturn($data);
                }

                $tourInfo = D('tour')->addTour();
                $keyid = Utils::getDecrypt(I('keyid'));

                if (I('tid')) {
                    $tid = I('tid');
                    if ($tid != $keyid) {
                        $data['status'] = 0;
                        $data['msg'] = '添加失败';
                        $this->ajaxReturn($data);
                    }
                } else {
                    $tid = $tourInfo;
                }

                if ($tourInfo) {
                    $data['status'] = 1;
                    $data['msg'] = '添加成功';
                    $data['url'] = U('Tour/add', array('id' => I('get.id'), 'tid' => $tid));
                    $this->ajaxReturn($data);
                } else {
                    $data['status'] = 0;
                    $data['msg'] = '添加失败';
                    $this->ajaxReturn($data);
                }
            }
        } else {
            $tour_id = I('get.tid');

            if ($tour_id == '' && $tour_id == null) {
                $id = 0;
            } else {
                $id = $tour_id;
            }
            if (I('get.tid')) {
                $tour = M('tour')->where('id=' . I('get.tid'))->find();
                $departure = explode(' ', $tour['departure']);
                if ($tour) {
                    $area = M('area')->where('name=' . "'" . $departure['0'] . "'")->find();
                    $this->city = M('area')->where('level=2 and parent_id=' . $area['id'])->select();
                }
            }

            $userId = session('user_id');
            $userInfo = M('user')->where("id = '{$userId}'")->field('id,name,mobile')->find();
            $this->assign('userInfo', $userInfo);

            $userProviderInfo = D('tour')->userInfo();
            $destinations = explode(',', $userProviderInfo['destinations']);
            $this->province = M('area')->where('level=1')->select();
            $this->aid = $id;
            $this->info = $userProviderInfo;
            $num = count($destinations);
            $this->num = $num;

            if ($num = 1) {
                $this->destination = $destinations;
            } else {
                $this->destination = $destinations;
            }

            $this->cityName = $userProviderInfo['addInfo']['destination']['0'];
            $this->display();
        }
    }

    /**
     * 供应商添加新的产品--行程
     */
    public function addPlan()
    {
        $tour_id = I('tid', 0, 'int');
        $keyid = Utils::getDecrypt(I('keyid'));
        $tourinfo = M('tour')->where('id=' . $tour_id)->count();
        $act = I('post.skuState');

        if (IS_POST && IS_AJAX) {
            if ($tourinfo > 0) {
                if (!I('post.addr') && !I('post.traffic') && !I('post.scenery') && !I('post.description') && !I('dining', '', 'trim')) {
                    $data['status'] = 1;
                    $data['msg'] = U('Tour/addPlan', array('id' => I('get.id'), 'tid' => $tour_id));
                    $this->ajaxReturn($data);
                } else {
                    if ($act == 'add') {
                        if ($this->warnStatus == '10404') {
                            $data['status'] = 0;
                            $data['msg'] = $this->warnInfo;
                            $this->ajaxreturn($data);
                        }

                        if ($tour_id != $keyid) {
                            $data['status'] = 0;
                            $data['msg'] = '添加失败';
                            $this->ajaxReturn($data);
                        }

                        $data = array(
                            'activity_addr' => I('post.activity_addr'),
                            'traffic' => I('post.traffic'),
                            'description' => I('post.description'),
                            'scenery' => I('post.scenery'),
                            'hotel' => I('post.hotel'),
                            'day' => I('day'),
                            'dining' => substr(I('dining', '', 'trim'), 0, strlen(I('dining', '', 'trim')) - 1),
                            'tour_id' => $tour_id,
                            'create_time' => date('Y-m-d H:i:s', time()),
                        );
                        $plan = M('tour_plan');
                        $planInfo = $plan->add($data);

                        if ($planInfo) {
                            $plan->where('id=' . $planInfo)->setField('day', $planInfo);
                            $data['status'] = 1;
                            $data['msg'] = '添加成功';
                            $this->ajaxReturn($data);
                        } else {
                            $data['status'] = 0;
                            $data['msg'] = '添加失败';
                            $this->ajaxReturn($data);
                        }
                    } else {
                        $data = array(
                            'id' => I('day'),
                            'activity_addr' => I('activity_addr'),
                            'traffic' => I('traffic'),
                            'description' => I('description'),
                            'scenery' => I('scenery'),
                            'hotel' => I('hotel'),
                            'day' => I('day'),
                            'dining' => substr(I('dining', ''), 0, strlen(I('dining', '')) - 1),
                            'update_time' => date('Y-m-d H:i:s', time()),
                        );
                        $plan = M('tour_plan');
                        $planEdit = $plan->save($data);

                        if ($planEdit) {
                            $data['status'] = 1;
                            $data['msg'] = '编辑成功';
                            $this->ajaxReturn($data);
                        } else {
                            $data['status'] = 0;
                            $data['msg'] = '编辑失败';
                            $this->ajaxReturn($data);
                        }
                    }
                }
            } else {
                $data['status'] = 2;
                $data['msg'] = '请先添加基本信息';
                $this->ajaxReturn($data);
            }
        } else {
            $this->info = M('tour_plan')->where('tour_id=' . $tour_id)->field('id,activity_addr,scenery,traffic,description,dining')->select();

            $this->aid = $tour_id;
            $this->count = count($this->info);
            $this->display();
        }
    }

    /**
     * 供应商添加新的产品--位控/团期
     */
    public function addSku()
    {
        $tour_id = I('tid', 0, 'int');
        $tourinfo = M('tour')->where('id=' . $tour_id)->count();

        if (IS_POST && IS_AJAX) {
            if ($tourinfo > 0) {
                if (!I('post.aoriginal') && !I('post.aagency') && !I('post.num')) {
                    $data['status'] = 1;
                    $data['msg'] = U('Tour/addSku', array('id' => I('get.id'), 'tid' => $tour_id));
                    $this->ajaxReturn($data);
                } else {
                    if ($this->warnStatus == '10404') {
                        $data['status'] = 0;
                        $data['msg'] = $this->warnInfo;
                        $this->ajaxreturn($data);
                    }

                    $keyid = Utils::getDecrypt(I('keyid'));

                    if ($tour_id != $keyid) {
                        $data['status'] = 0;
                        $data['msg'] = '添加失败';
                        $this->ajaxReturn($data);
                    }

                    if (D('tour')->addSku($tour_id, I('post.'))) {

                        $skuList = M('tour_sku')->where("tour_id = '{$tour_id}'")->field('id,start_time')->order("start_time desc")->find();
                        $tourData['latest_sku'] = $skuList['start_time'];
                        $tourData['update_time'] = date("Y-m-d H:i:s", time());
                        M('tour')->where("id = '{$tour_id}'")->save($tourData);
                        $data['status'] = 1;
                        $data['msg'] = '添加成功';
                        $this->ajaxReturn($data);
                    } else {
                        $data['status'] = 0;
                        $data['msg'] = '添加失败';
                        $this->ajaxReturn($data);
                    }
                }
            } else {
                $data['status'] = 2;
                $data['msg'] = '请先添加基本信息';
                $this->ajaxReturn($data);
            }
        } else {
            $where = " tour_id=" . $tour_id;
            $pageInfo = Utils::pages('tour_sku', $where, 25, $order = ' start_time desc ');
            $this->page = $pageInfo['page'];
            $this->info = $pageInfo['info'];
            //判断如果获取id失败时，则返回0
            if ($tour_id == '' && $tour_id == null) {
                $id = 0;
            } else {
                $id = $tour_id;
            }
            $this->assign('aid', $id);
            $this->display();
        }
    }

    /**
     * 常规-位控编辑
     */
    public function skuEdit()
    {
        if (IS_POST && IS_AJAX) {
            if (I('post.skuState') == 'edit' && I('post.skuState')) {
                if (D('tour')->skuEdit(I('post.'))) {

                    if ($this->warnStatus == '10404') {
                        $data['status'] = 0;
                        $data['msg'] = $this->warnInfo;
                        $this->ajaxreturn($data);
                    }

                    $skuId = I('tid');
                    $keyid = Utils::getDecrypt(I('keyid'));

                    if ($skuId != $keyid) {
                        $data['status'] = 0;
                        $data['msg'] = '编辑失败';
                        $this->ajaxReturn($data);
                    }

                    $skuInfo = M('tour_sku')->where("id = '{$skuId}'")->field('tour_id')->find();
                    $tourId = $skuInfo['tour_id'];
                    $skuList = M('tour_sku')->where("tour_id = '{$tourId}'")->field('id,start_time')->order('start_time desc')->find();

                    $now = date("Y-m-d 00:00:00");
                    $minInfo = M('tour_sku')->where("tour_id = '{$tourId}'")->field('id,min(price_adult_list) price_adult_list')->group('tour_id')->find();

                    if ($skuList) {
                        $tourData = $skuList['start_time'];
                        $minPrice = $minInfo['price_adult_list'];
                        $updateTime = date("Y-m-d H:i:s", time());
                        M('tour')->execute("update top_tour set latest_sku = '{$tourData}',min_price = '{$minPrice}',update_time = '{$updateTime}' where id = '{$tourId}'");
                    }

                    $data['status'] = 1;
                    $data['msg'] = '编辑成功';
                    $this->ajaxReturn($data);
                } else {
                    $data['status'] = 0;
                    $data['msg'] = '编辑失败';
                    $this->ajaxReturn($data);
                }
            } else {

                if ($infosku = D('tour')->skuEditOneInfo(I('post.id', '0', 'int'))) {
                    $data['status'] = 1;
                    $data['info'] = $infosku;
                    $this->ajaxReturn($data);
                } else {
                    return false;
                }
            }
        }
    }

    /**
     * 游轮-位控编辑
     */
    public function editCruiseSku()
    {
        if (IS_POST && IS_AJAX) {
            if (I('post.skuState') == 'edit' && I('post.skuState')) {
                if (D('tour')->CruiseSkuEdit(I('post.'))) {
                    if ($this->warnStatus == '10404') {
                        $data['status'] = 0;
                        $data['msg'] = $this->warnInfo;
                        $this->ajaxreturn($data);
                    }

                    $skuId = I('tid');
                    $keyid = Utils::getDecrypt(I('keyid'));
                    if ($skuId != $keyid) {
                        $data['status'] = 0;
                        $data['msg'] = '编辑失败';
                        $this->ajaxReturn($data);
                    }

                    $skuInfo = M('tour_sku')->where("id = '{$skuId}'")->field('tour_id')->find();
                    $tourId = $skuInfo['tour_id'];
                    $skuList = M('tour_sku')->where("tour_id = '{$tourId}'")->field('id,start_time')->order('start_time desc')->find();

                    if ($skuList) {
                        $tourData = $skuList['start_time'];
                        $updateTime = date("Y-m-d H:i:s", time());
                        M('tour')->execute("update top_tour set latest_sku = '{$tourData}',update_time = '{$updateTime}' where id = '{$tourId}'");
                    }

                    $data['status'] = 1;
                    $data['msg'] = '编辑成功';
                    $this->ajaxReturn($data);
                } else {
                    $data['status'] = 0;
                    $data['msg'] = '编辑失败';
                    $this->ajaxReturn($data);
                }
            } else {
                if ($infosku = D('tour')->skuEditOneInfo(I('post.id', '0', 'int'))) {
                    $data['status'] = 1;
                    $data['info'] = $infosku;
                    $this->ajaxReturn($data);
                } else {
                    return false;
                }
            }
        }
    }

    /**
     * 供应商添加新的产品--详细信息
     */
    public function addExtend()
    {
        $tour_id = I('tid', 0, 'int');

        if (IS_POST && IS_AJAX) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 0;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $keyid = Utils::getDecrypt(I('keyid'));
            if ($tour_id != $keyid) {
                $data['status'] = 1;
                $data['msg'] = '保存失败';
                $data['url'] = U('Tour/addExtend', array('id' => I('get.id'), 'tid' => $tour_id));
                $this->ajaxReturn($data);
            }

            $data = array(
                'description' => $_POST['description']['0'],
                'notice' => $_POST['notice']['0'],
                'fee_include' => $_POST['fee_include']['0'],
                'fee_exclude' => $_POST['fee_exclude']['0'],
                'update_time' => date('Y-m-d H:i:s', time()),
            );

            $result = D('Tour')->where('id=' . $tour_id)->setField($data);

            if ($result) {
                $data['status'] = 1;
                $data['msg'] = '保存成功';
                $data['url'] = U('Tour/addExtend', array('id' => I('get.id'), 'tid' => $tour_id));
                $this->ajaxReturn($data);
            } else {
                $data['status'] = 1;
                $data['msg'] = '保存失败';
                $data['url'] = U('Tour/addExtend', array('id' => I('get.id'), 'tid' => $tour_id));
                $this->ajaxReturn($data);
            }
        } else {
            if ($tour_id == '' && $tour_id == null) {
                $id = 0;
            } else {
                $id = $tour_id;
            }

            $info = D('tour')->userInfo();
            $this->assign('userInfo', $info['addInfo']);
            $this->assign('aid', $id);
            $this->assign('id', I('id'));
            $this->display();
        }
    }

    /**
     * 上架列表
     */
    public function putaway()
    {
        if (IS_AJAX && IS_POST) {
            $auditState = I('state', 0, 'int');
            $id = I('id', 0, 'int');
            $tour = M('tour')->where('id=' . $id)->setField('state', $auditState);

            if ($tour) {
                $this->ajaxReturn(1);
            } else {
                $this->ajaxReturn(0);
            }
        }
        $nowDate = date('Y-m-d 00:00:00', strtotime('-2 day'));
        $this->assign('nowDate', $nowDate);

        $entityId = session('entity_id');
        $state = Top::ProductStateIsSale;
        $name = trim(I('get.name'));
        $nameCode = substr($name, 0, 2);

        if ($nameCode == 10 && is_numeric($name)) {
            $code = substr($name, 2);
        }

        if (!empty($name)) {
            $where = "provider_id = '{$entityId}' && state = '{$state}' && (name like '%%$name%%' || id = '{$code}' || destination like '%%$name%%')";
        } else {
            $where = "provider_id = '{$entityId}' && state = '{$state}'";
        }

        $order = "id desc ";
        $pageInfo = Utils::pages('tour', $where, C('PAGE_SET'), $order);
        $info = array(
            'info' => $pageInfo['info'],
            'page' => $pageInfo['page'],
        );

        $this->assign('name', $name);
        $this->info = $info['info'];
        $this->page = $info['page'];
        $this->display();
    }

    /**
     * 下架列表
     */
    public function soldout()
    {
        if (IS_AJAX && IS_POST) {
            $auditState = I('state', 0, 'int');
            $id = I('id', 0, 'int');
            $tour = M('tour')->where('id=' . $id)->setField('state', $auditState);

            if ($tour) {
                $this->ajaxReturn(1);
            } else {
                $this->ajaxReturn(0);
            }
        }

        $nowDate = date('Y-m-d 00:00:00', strtotime('-2 day'));
        $this->assign('nowDate', $nowDate);

        $entityId = session('entity_id');
        $state = Top::ProductStateCanceled;
        $name = trim(I('get.name'));
        $nameCode = substr($name, 0, 2);

        if ($nameCode == 10 && is_numeric($name)) {
            $code = substr($name, 2);
        }

        if (!empty($name)) {
            $where = "provider_id = '{$entityId}' && state = '{$state}' && (name like '%%$name%%' || id = '{$code}' || destination like '%%$name%%')";
        } else {
            $where = "provider_id = '{$entityId}' && state = '{$state}'";
        }

        $order = "id desc ";
        $pageInfo = Utils::pages('tour', $where, C('PAGE_SET'), $order);
        $info = array(
            'info' => $pageInfo['info'],
            'page' => $pageInfo['page'],
        );

        $this->assign('name', $name);
        $this->info = $info['info'];
        $this->page = $info['page'];
        $this->display();
    }

    /**
     * 删除团期位控
     */
    public function skuDelete()
    {
        if (IS_POST && IS_AJAX) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 0;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $ids = I('action_code');
            $skuId = Utils::getDecrypt($ids[0]);
            $skuInfo = M('tour_sku')->where("id = '{$skuId}'")->field('tour_id')->find();
            $tourId = $skuInfo['tour_id'];

            foreach ($ids as $id) {
                $id = Utils::getDecrypt($id);
                $result = M('tour_sku')->where("id = '{$id}'")->delete();
            }

            $skuList = M('tour_sku')->where("tour_id = '{$tourId}'")->field('id,start_time')->order('start_time desc')->find();
            if ($skuList) {
                $tourData = $skuList['start_time'];
                M('tour')->execute("update top_tour set latest_sku = '{$tourData}' where id = '{$tourId}'");
            }

            if ($result) {
                $data['status'] = 1;
                $data['msg'] = '删除成功';
                $this->ajaxReturn($data);
            } else {
                $data['status'] = 0;
                $data['msg'] = '删除失败';
                $this->ajaxReturn($data);
            }
        }
    }

    /**
     * 编辑产品
     */
    public function edit()
    {
        $tourid = I('tid', 0, 'int');

        if (IS_POST && IS_AJAX) {
            $entityType = session('entity_type');

            if ($entityType == '3') {
                if ($this->warnStatus == '10404') {
                    $data['status'] = 0;
                    $data['msg'] = $this->warnInfo;
                    $this->ajaxreturn($data);
                }
            }

            $keyid = Utils::getDecrypt(I('keyid'));

            if ($tourid != $keyid) {
                $data['status'] = 0;
                $data['msg'] = '保存失败';
                $this->ajaxReturn($data);
            }

            if (I('post.city')) {
                $area = M('area')->where('name=' . "'" . I('post.city') . "'")->find();
                $city = M('area')->where('parent_id=' . $area['id'] . ' and level=2')->field('id,name')->select();
                $data = $city;
                $this->ajaxReturn($data);
            } else {
                $tourInfo = D('tour')->editTour(I('post.'), $tourid);
                if ($tourInfo) {
                    $data['status'] = 1;
                    $data['url'] = U('Tour/edit', array('id' => I('get.id'), 'tid' => I('tid', 0, 'int')));
                    $data['msg'] = '保存成功';
                    $this->ajaxReturn($data);
                } else {
                    $data['status'] = 0;
                    $data['msg'] = '保存失败';
                    $this->ajaxReturn($data);
                }
            }
        } else {
            $tourInfo = M('tour')->field('id,name,provider_id,line_type,departure,destination,destinations,start_time,pics,traffic_go,traffic_back,contact_person,cover_pic,promotion,contact_phone,travel_type')->find(I('get.tid'));
            $providerId = $tourInfo['provider_id'];
            $providerInfo = M('provider')->where("id = '{$providerId}'")->field('destinations')->find();
            $tourInfo['departure'] = explode(' ', $tourInfo['departure']);
            $tourInfo['destination1'] = explode(',', $providerInfo['destinations']);
            $infoPics = explode('@@@', $tourInfo['pics']);

            foreach ($infoPics as $k => $v) {
                $infoImgAll[$k] = explode('|', $v);
            }

            $tourInfo['imgs'] = $infoImgAll;
            $this->pic_num = count($infoImgAll) - 1;
            $this->province = M('area')->where('level=1')->select();
            $area = M('area')->where('name = ' . "'" . $tourInfo['departure']['0'] . "'")->find();
            $this->city = M('area')->where('level=2 and parent_id=' . $area['id'])->select();
            $tourInfo['provider'] = M('provider')->where('id=' . $tourInfo['provider_id'])->field('id,name')->find();
            $this->assign('tourInfo', $tourInfo);
            $this->display();
        }
    }

    /**
     * 编辑产品--行程
     */
    public function editPlan()
    {
        $id = I('get.tid', 0, 'int');
        $this->planInfo = M('tour_plan')->where('tour_id=' . $id)->select();
        $this->count = count($this->planInfo);
        $this->skuid = $id;
        $this->assign('tourId', $id);
        $this->display();
    }

    /**
     * editExtend 编辑产品--详细信息
     */
    public function extendEdit()
    {
        $tour_id = I('tid', 0, 'int');

        if (IS_POST && IS_AJAX) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 0;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $keyid = Utils::getDecrypt(I('keyid'));
            if ($tour_id != $keyid) {
                $data['status'] = 0;
                $data['msg'] = '保存失败';
                $data['url'] = U('Tour/addExtend', array('id' => I('get.id'), 'tid' => $tour_id));
                $this->ajaxReturn($data);
            }

            $data = array(
                'description' => $_POST['description']['0'],
                'notice' => $_POST['notice']['0'],
                'fee_include' => $_POST['fee_include']['0'],
                'fee_exclude' => $_POST['fee_exclude']['0'],
                'update_time' => date("Y-m-d H:i:s", time()),
            );
            $info = D('Tour')->where('id=' . $tour_id)->setField($data);

            if ($info) {
                $data['status'] = 1;
                $data['msg'] = '保存成功';
                $data['url'] = U('Tour/addExtend', array('id' => I('get.id'), 'tid' => $tour_id));
                $this->ajaxReturn($data);
            } else {
                $data['status'] = 0;
                $data['msg'] = '保存失败';
                $data['url'] = U('Tour/addExtend', array('id' => I('get.id'), 'tid' => $tour_id));
                $this->ajaxReturn($data);
            }
        } else {
            $id = I('get.tid', 0, 'int');
            $this->planInfo = M('tour')->field('description,notice,fee_include,fee_exclude')->find($id);
            $this->Extendid = $id;
            $this->display();
        }
    }

    /**
     * 编辑产品--位控团期
     */
    public function editSku()
    {
        $id = I('tid', 0, 'int');
        $where = " tour_id=" . $id;
        $pageInfo = Utils::pages('tour_sku', $where, 25, $order = " start_time desc ");

        $this->page = $pageInfo['page'];
        $this->skuInfo = $pageInfo['info'];
        $this->skuid = $id;
        $this->display();
    }

    /**
     * 新增游轮
     */
    public function addCruiseSku()
    {
        $tour_id = I('tid');
        $tourinfo = M('tour')->where('id=' . $tour_id)->count();

        if (IS_POST && IS_AJAX) {
            if ($tourinfo > 0) {
                $tour_id = I('tid');
                $times = I('times');
                $cruise = I('cruise');
                $min_price = Utils::getFen(I('min_price'));
                $dateTime = explode(',', $times);

                if ($this->warnStatus == '10404') {
                    $data['status'] = 0;
                    $data['msg'] = $this->warnInfo;
                    $this->ajaxreturn($data);
                }
                $keyid = Utils::getDecrypt(I('keyid'));
                if ($tour_id != $keyid) {
                    $data['status'] = 0;
                    $data['msg'] = '添加失败';
                    $this->ajaxReturn($data);
                }

                foreach ($dateTime as $v) {
                    $data = array(
                        'tour_id' => $tour_id,
                        'start_time' => $v,
                        'cruise' => $cruise,
                        'price_adult_list' => $min_price,
                        'price_adult_agency' => $min_price,
                        'state' => Top::ProductStateNotSubmitted,
                        'create_time' => date("Y-m-d H:i:s", time()),
                    );
                    $skuInfo = M('tour_sku')->add($data);
                }

                $skuList = M('tour_sku')->where("tour_id = '{$tour_id}'")->field('id,start_time')->order("start_time desc")->find();
                $tourData['latest_sku'] = $skuList['start_time'];
                $tourData['min_price'] = $min_price;
                M('tour')->where("id = '{$tour_id}'")->save($tourData);

                if ($skuInfo) {
                    $data['status'] = 1;
                    $data['msg'] = '添加成功';
                    $this->ajaxReturn($data);
                } else {
                    $data['status'] = 0;
                    $data['msg'] = '添加失败';
                    $this->ajaxReturn($data);
                }
            } else {
                $data['status'] = 2;
                $data['msg'] = '请先添加基本信息';
                $this->ajaxReturn($data);
            }
        } else {
            $where = " tour_id=" . $tour_id;
            $pageInfo = Utils::pages('tour_sku', $where, 25, $order = ' id asc ');
            $this->page = $pageInfo['page'];
            $this->info = $pageInfo['info'];
            //判断如果获取id失败时，则返回0
            if ($tour_id == '' && $tour_id == null) {
                $id = 0;
            } else {
                $id = $tour_id;
            }
            $this->assign('aid', $id);
            $this->display();
        }
    }

    /**
     * 编辑行程
     */
    public function planEdit()
    {
        $act = I('post.skuState');

        if (IS_POST && IS_AJAX) {
            if ($act == 'edit') {
                if ($this->warnStatus == '10404') {
                    $data['status'] = 0;
                    $data['msg'] = $this->warnInfo;
                    $this->ajaxreturn($data);
                }

                $tourid = I('tid');
                $keyid = Utils::getDecrypt(I('keyid'));

                if ($tourid != $keyid) {
                    $data['status'] = 0;
                    $data['msg'] = '编辑失败';
                    $this->ajaxReturn($data);
                }

                $data = array(
                    'id' => I('tid'),
                    'activity_addr' => I('activity_addr'),
                    'traffic' => I('traffic'),
                    'description' => I('description'),
                    'scenery' => I('scenery'),
                    'hotel' => I('hotel'),
                    'day' => I('day'),
                    'dining' => substr(I('dining', ''), 0, strlen(I('dining', '')) - 1),
                    'update_time' => date('Y-m-d H:i:s', time()),
                );
                $plan = M('tour_plan');
                $planEdit = $plan->save($data);

                if ($planEdit) {
                    $data['status'] = 1;
                    $data['msg'] = '编辑成功';
                    $this->ajaxReturn($data);
                } else {
                    $data['status'] = 0;
                    $data['msg'] = '编辑失败';
                    $this->ajaxReturn($data);
                }
            } else if ($act == "insert") {
                if ($this->warnStatus == '10404') {
                    $data['status'] = 0;
                    $data['msg'] = $this->warnInfo;
                    $this->ajaxreturn($data);
                }

                $tourid = I('tour_id');
                $keyid = Utils::getDecrypt(I('keyid'));
                if ($tourid != $keyid) {
                    $data['status'] = 0;
                    $data['msg'] = '添加失败';
                    $this->ajaxReturn($data);
                }

                $data = array(
                    'tour_id' => $tourid,
                    'activity_addr' => I('post.activity_addr'),
                    'traffic' => I('post.traffic'),
                    'description' => I('post.description'),
                    'scenery' => I('post.scenery'),
                    'hotel' => I('post.hotel'),
                    'dining' => substr(I('dining', ''), 0, strlen(I('dining', '')) - 1),
                    'create_time' => date('Y-m-d H:i:s', time()),
                );

                $plan = M('tour_plan');
                $planEdit = $plan->add($data);
                $day['day'] = $planEdit;
                $planEdit = $plan->where("id='{$planEdit}'")->save($day);

                if ($planEdit) {
                    $data['status'] = 1;
                    $data['msg'] = '添加成功';
                    $this->ajaxReturn($data);
                } else {
                    $data['status'] = 0;
                    $data['msg'] = '添加失败';
                    $this->ajaxReturn($data);
                }
            } else {
                $tour_plan = M('tour_plan')->where('id=' . I('post.id', 0, 'int'))->find();

                $arr = array(
                    'id' => $tour_plan['id'],
                    'tour_id' => $tour_plan['tour_id'],
                    'activity_addr' => $tour_plan['activity_addr'],
                    'day' => $tour_plan['day'],
                    'scenery' => $tour_plan['scenery'],
                    'traffic' => $tour_plan['traffic'],
                    'description' => $tour_plan['description'],
                    'hotel' => $tour_plan['hotel'],
                    'dining' => $tour_plan['dining'],
                    'create_time' => $tour_plan['create_time'],
                );

                if ($tour_plan) {
                    $data['status'] = 1;
                    $data['info'] = $arr;
                    $this->ajaxReturn($data);
                } else {
                    return false;
                }
            }
        }
    }

    /**
     * 删除行程
     */
    public function planDelete()
    {
        if (IS_POST && IS_AJAX) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 0;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $ids = I('action_code');

            foreach ($ids as $id) {
                $id = Utils::getDecrypt($id);
                $result = M('tour_plan')->where("id = '{$id}'")->delete();
            }

            if ($result) {
                $data['status'] = 1;
                $data['msg'] = '删除成功';
                $this->ajaxReturn($data);
            } else {
                $data['status'] = 0;
                $data['msg'] = '删除失败';
                $this->ajaxReturn($data);
            }
        }
    }

    /**
     * 删除产品
     */
    public function delete()
    {
        if (IS_POST && IS_AJAX) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 0;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $ids = I('action_code');

            foreach ($ids as $id) {
                $id = Utils::getDecrypt($id);
                $tourResult = M('tour')->where("id = '{$id}'")->delete();
                M('tour_plan')->where("tour_id = '{$id}'")->delete();
                M('tour_sku')->where("tour_id = '{$id}'")->delete();
            }

            if ($tourResult) {
                $data['status'] = 1;
                $data['msg'] = '删除成功';
                $this->ajaxReturn($data);
            } else {
                $data['status'] = 0;
                $data['msg'] = '删除失败';
                $this->ajaxReturn($data);
            }
        }
    }

    /**
     * 点击标题 - 查看详情
     */
    public function details()
    {
        $M = M();
        $id = I('id');

        $list = $M->table('top_tour as t')
            ->where("t.id=$id")
            ->field(array(
                't.id' => 'id',
                't.name' => 'name',
                't.provider_name' => 'provider_name',
                't.traffic_go' => 'traffic_go',
                't.traffic_back' => 'traffic_back',
                't.min_price' => 'min_price',
                't.departure' => 'departure',
                't.destinations' => 'destinations',
                't.pics' => 'pics',
                't.notice' => 'notice',
                't.description' => 'tour_description',
                't.fee_include' => 'fee_include',
                't.fee_exclude' => 'fee_exclude',
            ))
            ->find();

        $departure = explode(" ", $list['departure']);

        if ($departure['0'] == $departure['1']) {
            unset($departure['1']);
            $departure = implode(" ", $departure);
        } else {
            $departure = implode(" ", $departure);
        }

        $tour_description = $M->table('top_tour_plan as p')
            ->where("p.tour_id = '{$id}'")
            ->order('p.day asc')
            ->field(array(
                'p.day' => 'day',
                'p.description' => 'description',
                'p.hotel' => 'hotel',
                'p.dining' => 'dining',
            ))
            ->select();

        $totalDay = count($tour_description);
        $today = date('Y-m-d 24:00:00', strtotime('+1 day'));

        $skuInfo = M('tour_sku')->where("tour_id = '{$id}' && start_time > '{$today}'")->field("id,cruise,start_time")->select();

        $cruise = array();
        foreach ($skuInfo as $key => $vo) {
            $cruise[] = explode(';', $vo['cruise']);
        }

        $cruiseArr = array();
        foreach ($cruise as $key => $v) {
            $v = array_filter($v);
            foreach ($v as $k => $vo) {
                $cruiseArr[$key][$k] = explode(',', $vo);
            }
        }

        $this->assign('cruiseArr', $cruiseArr);
        $tourId = $list['id'];
        $tourSku = M('tour_sku')->where("tour_id = '{$tourId}' && start_time > '{$today}'")->select();

        foreach ($tourSku as $key => $vo) {
            $tourSkuDate[$key]['id'] = $vo['id'];
            $tourSkuDate[$key]['price_adult_list'] = $vo['price_adult_list'];
            $tourSkuDate[$key]['price_child_list'] = $vo['price_child_list'];
            $tourSkuDate[$key]['start_time'] = substr($vo['start_time'], 0, 10);
        }

        $Pics = explode("@@@", $list['pics']);
        array_pop($Pics);

        $picArr = array();
        foreach ($Pics as $vo) {
            $picArr[] = Utils::GetImageUrl(str_replace("#file1#", C('FILE1_BASE_URL'), substr($vo, 0, strpos($vo, '|'))), 240, 160, 1);
        }

        $this->assign('departure', $departure);
        $this->assign('tourSkuDate', $tourSkuDate);
        $this->assign('tour_description', $tour_description);
        $this->assign('totalDay', $totalDay);
        $this->assign('list', $list);
        $this->assign('picArr', $picArr);
        $this->assign('today', $today);
        $this->display();
    }


    public function morePics()
    {
        $id = I('get.id');
        $list = M('tour')->where("id = '{$id}'")->find();
        $Pics = explode("@@@", $list['pics']);
        array_pop($Pics);
        $picArr = array();

        foreach ($Pics as $vo) {
            $picArr[] = array(
                'img' => Utils::GetImageUrl(str_replace("#file1#", C('FILE1_BASE_URL'), substr($vo, 0, strpos($vo, '|'))), 600, 800, 0),
                'name' => substr($vo, strpos($vo, '|') + 3)
            );
        }

        $this->assign('list', $list);
        $this->assign('picArr', $picArr);
        $this->display();
    }


    /**
     * 临时二维码
     */
    public function temporary()
    {
        vendor('WxPayPubHelper.WxPayPubHelper');
        $jsApi = new \JsApi_pub();
        $accessToken = $jsApi->getAccessToken();
        $sceneId = "1" . rand(0, 999999);
        $data['expire_seconds'] = '86400';
        $data['action_name'] = 'QR_SCENE';
        $data['action_info'] = array(
            'scene' => array(
                'scene_id' => intval($sceneId),
            ),
        );
        $ruleData['key'] = $sceneId;
        $ruleData['user_id'] = session('user_id');
        $ruleData['action'] = 'bind-notify-msg';
        $ruleData['expire_time'] = '86400';
        $ruleData['create_time'] = date("Y-m-d H:i:s", time());
        M('scan_rule')->add($ruleData);

        $data = json_encode($data);
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=$accessToken";
        $result = Utils::vpost($url, $data);
       
        $resultObject = json_decode($result);//object
      
        $resultArray = $this->object_to_array($resultObject);//array
        $url = $resultArray['url'];
        
        $level = 'L';
        $size = 5;
        Vendor('phpqrcode.phpqrcode');
        $errorCorrectionLevel = intval($level);
        $matrixPointSize = intval($size);

        $object = new \QRcode();
        $object->png($url, false, $errorCorrectionLevel, $matrixPointSize);
    }


    public function userInfo()
    {
        if (IS_POST && IS_AJAX) {
            $where['id'] = I('id');
            $userInfo = M('user')->where($where)->find();
            $openId = $userInfo['weixinmp_openid'];

            if (!empty($openId)) {
                $data['status'] = 1;
                $this->ajaxReturn($data);
            }
        }
    }

}